package com.android.vgongyi.common;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.image.CacheTask;
import com.android.image.TPManager;
import com.android.vgongyi.R;
import com.android.vgongyi.activity.CheckCommentActivity;
import com.android.vgongyi.activity.HomePageActivity;
import com.android.vgongyi.activity.ReplyActivity;
import com.android.vgongyi.activity.SaveImageActivity;
import com.android.vgongyi.activity.TransferActivity;
import com.android.vgongyi.dao.CommonDAO;
import com.android.vgongyi.dao.FavorateDAO;
import com.android.vgongyi.entity.CommonEntity;
import com.android.vgongyi.utils.AsyncImageLoader;
import com.android.vgongyi.utils.AsyncImageLoader.ImageCallback;
import com.android.vgongyi.utils.StringUtil;
import com.android.vgongyi.utils.SystemUtil;

public class FavorateAdapter extends BaseAdapter{
    
	private ArrayList<CommonEntity> mEntitylist;
    private Context 				context;
    private WeiboEntity 			mModuel;
    private LayoutInflater		 	mLayoutInflater;
    private AsyncImageLoader 		asyncImageLoader;
    private ListView 				listView;
    private int 					curPosition;
    private Handler					mHandler;
    private TPManager				tm;
    public FavorateAdapter(ArrayList<CommonEntity> list,Context ctx,ListView listView,Handler handler)
    {
    	this.mEntitylist		= list;
    	this.context			= ctx;
    	this.mLayoutInflater 	= LayoutInflater.from(ctx);
    	this.asyncImageLoader	= new AsyncImageLoader();
    	this.listView 			= listView;
    	this.mHandler			= handler;
    	this.tm					= TPManager.getInstance();
    }
    
	public int getCount() {
		return mEntitylist.size();
	}

	public Object getItem(int position) {
		return mEntitylist.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View view, ViewGroup parent) {
		curPosition = position;
		final CommonEntity tempCommonEntity = mEntitylist.get(position);
		if(view == null)
		{
			mModuel =  new WeiboEntity();
			view = mLayoutInflater.inflate(R.layout.item_home, null);
			mModuel.image_add_to_favourate	=(LinearLayout) view.findViewById(R.id.add_to_favourate);
			//mModuel.image_add_to_favourate.setVisibility(View.GONE);
			mModuel.image_dispatch			=(LinearLayout) view.findViewById(R.id.dispatch);
			mModuel.image_face				=(ImageView) view.findViewById(R.id.image_face);
			mModuel.image_face_vertify 		= (ImageView)view.findViewById(R.id.image_face_vertify);
			mModuel.image_vie_comments		=(LinearLayout) view.findViewById(R.id.check_comments);
			mModuel.image_detail_main 		= (ImageView)view.findViewById(R.id.weibo_img);
			mModuel.text__remark			=(TextView) view.findViewById(R.id.text__remark);
			mModuel.text_dispatch			=(TextView) view.findViewById(R.id.text_dispatch);
			mModuel.text_favourate			=(TextView) view.findViewById(R.id.text_favourate);
			mModuel.text_image_vie_comments	=(TextView) view.findViewById(R.id.text_image_vie_comments);
			mModuel.text_main				=(TextView) view.findViewById(R.id.text_main);
			mModuel.text_name				=(TextView) view.findViewById(R.id.text_name);
			mModuel.text_time_stamp			=(TextView) view.findViewById(R.id.text_time_stamp);
			mModuel.text_website_logo		=(ImageView) view.findViewById(R.id.text_website_logo);
			mModuel.weibo_img_layout		=(LinearLayout) view.findViewById(R.id.weibo_img_layout);
			mModuel.layout_user_img 		= (FrameLayout) view.findViewById(R.id.layout_user_img);
			view.setTag(mModuel);
		}
		else{
			mModuel=(WeiboEntity) view.getTag();
		}
		
		OnClickListener listener  =  new OnClickListener() {
			
			public void onClick(View v) {
				
				switch(v.getId())
				{
				case R.id.check_comments:
					if( Integer.valueOf(tempCommonEntity.getComment_nums()) == 0){
						Toast.makeText(context, context.getResources().getString(R.string.reply_no_comments), Toast.LENGTH_SHORT).show();
//						Intent intent = new Intent();
//						intent.setClass(context, ReplyActivity.class);
//						intent.putExtra("weiboID", tempCommonEntity.getWeibo_id());
//						intent.putExtra("weiboPlatform", tempCommonEntity.getWeibo_platform());
//						context.startActivity(intent);
					}else{
						Intent intent = new Intent();
						intent.setClass(context, CheckCommentActivity.class);
						intent.putExtra("itemId", tempCommonEntity.getId());
						intent.putExtra("commentSum", tempCommonEntity.getComment_nums());
						intent.putExtra("weiboPlatform", tempCommonEntity.getWeibo_platform());
						intent.putExtra("weiboID", tempCommonEntity.getWeibo_id());
						context.startActivity(intent);
					}
					break;
				case R.id.dispatch:
					Intent dispatchIntent = new Intent(context,TransferActivity.class);
			        dispatchIntent.putExtra("weiboContent", tempCommonEntity.getContent());
			        dispatchIntent.putExtra("weiboImg", tempCommonEntity.getImg_url());
			        dispatchIntent.putExtra("weibo_platform", tempCommonEntity.getWeibo_platform());
			        dispatchIntent.putExtra("weiboId", tempCommonEntity.getWeibo_id());
					context.startActivity(dispatchIntent);
					break;
				case R.id.weibo_img:
					Intent intentImg= new Intent(context,SaveImageActivity.class);
					intentImg.putExtra("imageUrl",tempCommonEntity.getImg_url());
					intentImg.putExtra("imageHeight",tempCommonEntity.getBig_height());
					intentImg.putExtra("imageWidth",tempCommonEntity.getBig_width());
					intentImg.putExtra("img_extension",tempCommonEntity.getImg_extension());
					context.startActivity(intentImg);
					break;
				case R.id.layout_user_img:
					Intent intentHomepage= new Intent(context,HomePageActivity.class);
					intentHomepage.putExtra("weiboUrl",tempCommonEntity.getWeibo_url());
					context.startActivity(intentHomepage);
					break;
				case R.id.add_to_favourate:
					abolish(tempCommonEntity.getId());
					mHandler.sendEmptyMessage(0);
					FavorateAdapter.this.notifyDataSetChanged();
					//Toast.makeText(context,context.getResources().getString(R.string.favorite_dec), Toast.LENGTH_SHORT).show();
					break;
				}
				
			}
		};
		
		mModuel.text_favourate.setText(R.string.favorite_dec);
		
		mModuel.image_vie_comments.setOnClickListener(listener);
		mModuel.image_detail_main.setOnClickListener(listener);
		mModuel.image_dispatch.setOnClickListener(listener);
		mModuel.layout_user_img.setOnClickListener(listener);
		mModuel.image_add_to_favourate.setOnClickListener(listener);
		
		String imageUrl = tempCommonEntity.getProfile_imageurl();
		
		String imageVertifyUrl = tempCommonEntity.getVerified();
		if (imageVertifyUrl.equals(AppConstant.NO_1)) {
			mModuel.image_face_vertify.setVisibility(View.VISIBLE);
		}
		
		mModuel.image_face.setTag(imageUrl);
        Drawable cachedImage = asyncImageLoader.loadDrawable(context,position, imageUrl,"", new ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl,String img_extension) {
            	
                ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                
                if (imageViewByTag != null && imageDrawable != null) { 
                    imageViewByTag.setImageDrawable(imageDrawable);
                }
            }
        });
        if (cachedImage == null) mModuel.image_face.setImageResource(R.drawable.weibosina);
        else 					 mModuel.image_face.setImageDrawable(cachedImage);

		
      	float big_h= Float.valueOf(tempCommonEntity.getBig_height());
      	float big_w= Float.valueOf(tempCommonEntity.getBig_width());
      	LayoutParams params;
      	if(big_w!=0){
      		params = new LinearLayout.LayoutParams(SystemUtil.getImageWidthSize(context),SystemUtil.getImageHeightSize(context, big_h, big_w));
      		mModuel.weibo_img_layout.setLayoutParams(params);
      	}
        
        String imageUrl2 = tempCommonEntity.getImg_url();
        
        tm.addTask(new CacheTask(imageUrl2, mModuel.image_detail_main));
		
		mModuel.text_name.setText(tempCommonEntity.getWriter_name());
		mModuel.text__remark.setText(tempCommonEntity.getVerified_reason());	
		String spaceTime = StringUtil.getSpaceTime(tempCommonEntity.getInsert_date());
		mModuel.text_time_stamp.setText(String.format(context.getResources().getString(R.string.from),spaceTime));
		mModuel.text_website_logo.setImageResource(weiboPlatform(tempCommonEntity.getWeibo_platform()));
		mModuel.text_main.setText(tempCommonEntity.getContent());
		
		if(null == tempCommonEntity.getComment_nums()){
			mModuel.text_image_vie_comments.setText(String.format(context.getResources().getString(R.string.check_comment),"0"));   
		}else{
			mModuel.text_image_vie_comments.setText(String.format(context.getResources().getString(R.string.check_comment),tempCommonEntity.getComment_nums()));  
		}
	    return view;
	}
	
	public int weiboPlatform(String platform){
		int imageResource;
		if(platform.equals(AppApiPreference.weiboPlatform[0])){
			imageResource = R.drawable.weibosinasmall;
		}else if(platform.equals(AppApiPreference.weiboPlatform[1])){
			imageResource = R.drawable.weibotencentsmall;
		}else if(platform.equals(AppApiPreference.weiboPlatform[3])){
			imageResource = R.drawable.weibo163small;
		}else{
			imageResource = R.drawable.weibosohusmall;
		}
		return imageResource;
	}

	public void abolish(String id){
		FavorateDAO favorateDAO = new FavorateDAO(context);
		CommonEntity tempCommonEntity = favorateDAO.query(null, "id='"+id+"'", null, null).get(0);
		favorateDAO.delete("id="+id, null);
		this.notifyDataSetChanged();
		
		tempCommonEntity.setFavourite(false);
		CommonDAO commonDAO = new CommonDAO(context);
		commonDAO.update(tempCommonEntity, "id = '"+tempCommonEntity.getId()+"'", null);
		
		}
	
	public class WeiboEntity {
	     public ImageView image_face;
	     public ImageView image_face_vertify;
	     public TextView text_name;
	     public TextView text__remark;
	     public TextView text_time_stamp;
	     public ImageView text_website_logo;
	     public TextView text_main;
	     public ImageView image_detail_main;
	     public LinearLayout image_dispatch;
	     public TextView text_dispatch;
	     public LinearLayout image_add_to_favourate;
	     public TextView text_favourate;
	     public LinearLayout image_vie_comments;
	     public TextView text_image_vie_comments;
	     public LinearLayout weibo_img_layout;
	     public FrameLayout layout_user_img;
	}

}
